import { createRouter, createWebHashHistory } from "vue-router";

const router = createRouter({
  // import.meta.env.BASE_URL
  history: createWebHashHistory(),
  routes: [
    {
      path: "/",
      redirect: "/login",
    },
    {
      path: "/login",
      component: () => import("@/views/login.vue"),
    },
    {
      path: "/home",
      component: () => import("@/layouts/Home.vue"),
      redirect: "/userList",
      children: [
        {
          path: "/userList",
          component: () => import("@/views/userList.vue"),
        },
        {
          path: "/permissionList",
          component: () => import("@/views/permissionList.vue"),
        },
        {
          path: "/logList",
          component: () => import("@/views/logList.vue"),
        },
        {
          path: "/mapManage1",
          component: () => import("@/views/mapManage1.vue"),
        },
        {
          path: "/mapManage2",
          component: () => import("@/views/mapManage2.vue"),
        },
        {
          path: "/mapManage3",
          component: () => import("@/views/mapManage3.vue"),
        },
        {
          path: "/mapManage4",
          component: () => import("@/views/mapManage4.vue"),
        },
      ],
    },
  ],
});

router.beforeEach((to, from, next) => {
  console.log("路由即将改变");
  // 检查用户是否已登录，如果没有登录则重定向到登录页面
  if (
    to.path !== "/login" &&
    (sessionStorage.getItem("token") == "" ||
      sessionStorage.getItem("token") == null)
  ) {
    return next({ path: "/login" }); // 重定向到登录页面
  } else {
    next(); // 确保一定要调用 next()
  }
});

export default router;
